package com.cloud.server.system.controller;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.cloud.common.core.base.ApiResponse;
import com.cloud.server.system.dto.QueryUserDTO;
import com.cloud.server.system.dto.UserInputDTO;
import com.cloud.server.system.mapper.entity.SystemUser;
import com.cloud.server.system.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Map;

/**
 * @author: Dream_xun
 * @date: 2020-08-24 0:51
 * @description:
 */
@RestController()
@RequiredArgsConstructor
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    private IUserService userService;

    /**
     * 查找用户详细信息
     *
     * @param queryUserDTO 用户查询对象，用于传递查询条件
     * @return Ipage
     */
    @GetMapping("/listUser")
    @PreAuthorize("hasAnyAuthority('user:view')")
    ApiResponse<Map<String, Object>> listUser(QueryUserDTO queryUserDTO){
        return ApiResponse.respond(userService.listUser(queryUserDTO));
    };

    /**
     * 新增用户
     * @param userInputDTO
     * @return
     */
    @PostMapping("/add")
    @PreAuthorize("hasAnyAuthority('user:add')")
    ApiResponse add(@RequestBody @Valid UserInputDTO userInputDTO){
        return ApiResponse.respond(userService.addUser(userInputDTO));
    };

    /**
     * 编辑用户
     * @param user
     * @return
     */
    @PutMapping("/edit")
    @PreAuthorize("hasAnyAuthority('user:update')")
    ApiResponse edit(@RequestBody @Valid SystemUser user){
        return ApiResponse.respond(userService.editUser(user));
    };

    /**
     * 查找用户
     * @param userId
     * @return
     */
    @GetMapping("/{userId}")
    ApiResponse<SystemUser> findByUserId(@PathVariable(value = "userId") Long userId){
        return ApiResponse.respond(userService.findByUserId(userId));
    };

    /**
     * 删除用户
     * @param userIds 用户 id数组
     * @return
     */
    @DeleteMapping("/{userIds}")
    @PreAuthorize("hasAnyAuthority('user:delete')")
    ApiResponse deleteByUserIds(@NotBlank(message = "userIds不能为空")String userIds){
        String[] ids = userIds.split(StringPool.COMMA);
        return ApiResponse.respond(userService.deleteByUserIds(ids));
    };
}
